//
//  MHChuyenDeViewController.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHChuyenDeViewController.h"
#import "Contants.h"
#import "TTScrollSlidingPagesController.h"
#import "TTSlidingPage.h"
#import "TTSlidingPageTitle.h"
#import "Lib.h"
#import "Topic.h"
#import "TopicHeader.h"
#import "TopicTableViewCell.h"
#import "MHGameCell.h"
#import "Application.h"
#import "UIImageView+WebCache.h"
#import "MHGameDetailViewController.h"
#import "MHAppDelegate.h"
#import "MHAppListViewController.h"


@interface MHChuyenDeViewController ()
{
    BOOL latestFirstLoad, recommendFirstLoad, phanLoaiFirstLoad;
}
@property (weak, nonatomic) IBOutlet UIButton *latestButton;
@property (weak, nonatomic) IBOutlet UIButton *recomendButton;
@property (weak, nonatomic) IBOutlet UIButton *phanLoaiButton;
@property (weak, nonatomic) IBOutlet UIView *topView;

@property (nonatomic, strong) MHNavibarView* navibarView;

@property (strong, nonatomic) TTScrollSlidingPagesController *mySlider;

@property (nonatomic, weak) IBOutlet UITableView* tableView;

@property (strong, nonatomic) IBOutlet UITableViewController *latestTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *recommendTableView;
@property (strong, nonatomic) IBOutlet UITableViewController *phanLoaiTableView;

@property (nonatomic, assign) int       currentIndexPage;
@end

@implementation MHChuyenDeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.navibarView = [MHNavibarView createWithLeftButton:kFileBtnHuman rightButton:nil searchButton:YES];
    [self.navibarView setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:nil search:nil];
    [self.navibarView setRootViewController:self];
    [self.view addSubview:self.navibarView];

    //initial setup of the TTScrollSlidingPagesController
    self.mySlider = [[TTScrollSlidingPagesController alloc] init];

    //set properties to customiser the slider. Make sure you set these BEFORE you access any other properties on the slider, such as the view or the datasource. Best to do it immediately after calling the init method.
    //self.slider.hideStatusBarWhenScrolling = YES;
    self.mySlider.titleScrollerHidden = YES;
    //slider.titleScrollerHeight = 100;
    //slider.titleScrollerItemWidth=60;
    //slider.titleScrollerBackgroundColour = [UIColor darkGrayColor];
    //slider.disableTitleScrollerShadow = YES;
    self.mySlider.disableUIPageControl = YES;
    //slider.initialPageNumber = 1;
    //slider.pagingEnabled = NO;
    //slider.zoomOutAnimationDisabled = YES;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7){
        self.mySlider.hideStatusBarWhenScrolling = YES;//this property normally only makes sense on iOS7+. See the documentation in TTScrollSlidingPagesController.h. If you wanted to use it in iOS6 you'd have to make sure the status bar overlapped the TTScrollSlidingPagesController.
    }

    //set the datasource.
    self.mySlider.dataSource = self;
    self.mySlider.delegate = self;

    //add the slider's view to this view as a subview, and add the viewcontroller to this viewcontrollers child collection (so that it gets retained and stays in memory! And gets all relevant events in the view controller lifecycle)
    CGRect frame = self.view.frame;
    frame.origin.y += self.topView.frame.size.height + self.navibarView.frame.size.height;
    frame.size.height -= (self.topView.frame.size.height + self.navibarView.frame.size.height);
    self.mySlider.view.frame = frame;
    [self.view addSubview:self.mySlider.view];
    [self addChildViewController:self.mySlider];

    [self.view setBackgroundColor:[UIColor whiteColor]];

    [self latestButtonPressed:nil];
}


#pragma mark - Navibar Button action
- (void)leftButtonPressed:(id)sender {
    [[MHAppDelegate sharedApp].viewController showLeftPanelAnimated:YES];
}

- (void)rightButtonPressed:(id)sender {

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)refresh {
    [Lib showLoadingView];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (self.tableView == self.latestTableView.tableView) {
            self.data = [Application appsFromServiceUrl:[NSString stringWithFormat:@"http://mobile.mho.vn/services/Game?IdCategoryGame=0&IdSystem=2&IdGroup=0&isHot=0&isNews=1&isMostView=0&pageIndex=0&pageSize=10&key=%@", kServerKey]].mutableCopy;
        }
        else if (self.tableView == self.recommendTableView.tableView) {
            self.data = [Topic topicFromCat:@"0"];
        }
        else if (self.tableView == self.phanLoaiTableView.tableView) {
            self.data = [Topic topicFromCat:@"0"];
        }
        _currentIndexPage = 1;

        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoading];
            [self.tableView reloadData];
        });
    });
}

- (void)loadingMore {
//    [Lib showLoadingView];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (self.tableView == self.latestTableView.tableView) {
            NSArray* array = [Application appsFromServiceUrl:[NSString stringWithFormat:@"http://mobile.mho.vn/services/Game?IdCategoryGame=0&IdSystem=2&IdGroup=0&isHot=0&isNews=1&isMostView=0&pageIndex=%d&pageSize=10&key=%@", _currentIndexPage, kServerKey]].mutableCopy;
            ++_currentIndexPage;
            
            [self.data addObjectsFromArray:array];
        }
        else if (self.tableView == self.recommendTableView.tableView) {
            self.data = [Topic topicFromCat:@"0"];
        }
        else if (self.tableView == self.phanLoaiTableView.tableView) {
            self.data = [Topic topicFromCat:@"0"];
        }
        _currentIndexPage = 1;
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            [Lib removeLoadingView];
             [self stopLoadingMore];
            [self.tableView reloadData];
        });
    });

}


#pragma mark - UITableView Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.recommendTableView.tableView) {
        return self.data.count;
    }
    if (tableView == self.phanLoaiTableView.tableView) {
        return self.data.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.recommendTableView.tableView) {
        return 1;
    }
    if (tableView == self.phanLoaiTableView.tableView) {
        return 1;
    }
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.latestTableView.tableView) {
        return 85;
    }
    return 70;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* cellIdentifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        if (tableView == self.latestTableView.tableView) {
            cell = [MHGameCell cellFromNib];
        }
        else if (tableView == self.recommendTableView.tableView) {
            cell = [TopicTableViewCell cellFromNib];
        }
        else if (tableView == self.phanLoaiTableView.tableView) {
            cell = [TopicTableViewCell cellFromNib];
        }
        else {
            cell = [[UITableViewCell alloc] init];
        }
    }

    // Configure cell
    if (tableView == self.latestTableView.tableView) {
        MHGameCell* gCell = (MHGameCell*)cell;
        Application* app = [self.data objectAtIndex:indexPath.row];
        if (app && [app isKindOfClass:[Application class]]) {
            [gCell setApp:app];
        }
    }


    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.recommendTableView.tableView) {
        return 20;
    }
    if (tableView == self.phanLoaiTableView.tableView) {
        return 20;
    }
    return 0;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString* headerIdentifier = @"View";
    UIView* view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier];
    if (!view) {
        if (tableView == self.recommendTableView.tableView) {
            view = [TopicHeader viewFromNib];
        }
        else if (tableView == self.phanLoaiTableView.tableView) {
            view = [TopicHeader viewFromNib];
        }
        else {
            view = [[UIView alloc] init];
        }
    }
    // COnfigure
    if (tableView == self.recommendTableView.tableView) {
        Topic* topic = [self.data objectAtIndex:section];
        if (topic && [topic isKindOfClass:[Topic class]]) {
            TopicHeader* header = (TopicHeader*)view;
            [header setTopicName:topic.topicName];
        }
    }
    else if (tableView == self.phanLoaiTableView.tableView) {
        Topic* topic = [self.data objectAtIndex:section];
        if (topic && [topic isKindOfClass:[Topic class]]) {
            TopicHeader* header = (TopicHeader*)view;
            [header setTopicName:topic.topicName];
        }
    }
    else {

    }

    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.latestTableView.tableView) {
        Application* app = self.data[indexPath.row];
        if (app && [app isKindOfClass:[Application class]]) {
            MHGameDetailViewController* vc = [[MHGameDetailViewController alloc] initWithNibName:@"MHGameDetailViewController" bundle:nil];
            [vc setApp:app];
            [vc setAppId:app.appId.integerValue];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    else {
        Topic* topic = self.data[indexPath.section];
        NSLog(@"data: %@ index: %ld", self.data, (long)indexPath.section);
        if (topic && [topic isKindOfClass:[Topic class]]) {
            MHAppListViewController* vc = [[MHAppListViewController alloc] initWithNibName:@"MHAppListViewController" bundle:nil];
            vc.listUrl = [NSString stringWithFormat:@"http://mobile.mho.vn/services/topic?IdToppic=%@&IdSystem=2&IdGroup=1&pageIndex=%@&pageSize=%@&key=%@", topic.topicId, @"%d", @"%d", kServerKey];
            NSLog(@"list url: %@", vc.listUrl);
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (IBAction)latestButtonPressed:(id)sender {
    [self.mySlider scrollToPage:0 animated:YES];
    [self.latestButton setEnabled:NO];
    [self.recomendButton setEnabled:YES];
    [self.phanLoaiButton setEnabled:YES];

    self.tableView = self.latestTableView.tableView;

    if (!latestFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }
}

- (IBAction)recommendButtonPressed:(id)sender {
    [self.mySlider scrollToPage:1 animated:YES];
    [self.latestButton setEnabled:YES];
    [self.recomendButton setEnabled:NO];
    [self.phanLoaiButton setEnabled:YES];

    self.tableView = self.recommendTableView.tableView;

    if (!recommendFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }
}
- (IBAction)phanLoaiButtonPressed:(id)sender {
    [self.mySlider scrollToPage:2 animated:YES];
    [self.latestButton setEnabled:YES];
    [self.recomendButton setEnabled:YES];
    [self.phanLoaiButton setEnabled:NO];

    self.tableView = self.phanLoaiTableView.tableView;

    if (!phanLoaiFirstLoad) {
        //        firstAppRequest = YES;
        [self refresh];
    }
}


#pragma mark TTSlidingPagesDataSource methods
-(NSInteger)numberOfPagesForSlidingPagesViewController:(TTScrollSlidingPagesController *)source{
    return 3;
}

-(TTSlidingPage *)pageForSlidingPagesViewController:(TTScrollSlidingPagesController*)source atIndex:(NSInteger)index{
    UIViewController *viewController;
    if (index == 0) {
        viewController = self.latestTableView;
    }
    else if (index == 1) {
        viewController = self.recommendTableView;
    }
    else {
        viewController = self.phanLoaiTableView;
    }
    CGRect frame = self.mySlider.view.frame;
    frame.origin.y = 0;
    //    frame.size.height -= self.topView.frame.size.height;
    [viewController.view setFrame:frame];

    return [[TTSlidingPage alloc] initWithContentViewController:viewController];
}

-(TTSlidingPageTitle *)titleForSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(NSInteger)index{
    TTSlidingPageTitle *title;
    if (index == 0){
        //use a image as the header for the first page
        title= [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top App"];
    } else {
        //all other pages just use a simple text header
        title = [[TTSlidingPageTitle alloc] initWithHeaderText:@"Top Game"];

    }
    return title;
}

////The below method in the datasource might get removed from the control some time in the future as it doesn't work that well with the headers if the width is small.
//-(int)widthForPageOnSlidingPagesViewController:(TTScrollSlidingPagesController *)source atIndex:(int)index
//{
//    if (index ==3){
//        return 130;
//    } else {
//        return self.view.frame.size.width;
//    }
//}

#pragma mark - delegate
-(void)didScrollToViewAtIndex:(NSUInteger)index
{
    if (index == 0) {
        //        self.tableView = self.topAppTableView.tableView;
        //        self.group = kGroupApp;
        [self latestButtonPressed:nil];
    }
    else if (index == 1){
        //        self.tableView = self.topGameTableView.tableView;
        //        self.group = kGroupGame;
        [self recommendButtonPressed:nil];
    }
    else {
        [self phanLoaiButtonPressed:nil];
    }
    //    [self refresh];
}

@end
